package com.woniuxy.userapp.app.controller;



import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.authapp.client.AuthClient;
import com.woniuxy.commons.util.Result;
import com.woniuxy.commons.util.WebUtil;
import com.woniuxy.userapp.app.controller.info.LoginApp;
import com.woniuxy.userapp.client.BackgroundAccountClient;
import com.woniuxy.userapp.client.param.LoginInfo;
import com.woniuxy.userapp.client.param.UserInfo;
import com.woniuxy.userapp.service.BackgroundAccountService;
import com.woniuxy.userapp.service.constant.AuthConstant;
import com.woniuxy.userapp.service.dto.UserDto;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  后台账户
 * </p>
 *
 * @author 
 * @since 2022-08-03
 */
@RestController
public class BackgroundAccountController implements BackgroundAccountClient {

    @Autowired
    private AuthClient authClient;
    @Autowired
    private BackgroundAccountService backgroundAccountService;

    @Override
    public Result<UserInfo> BloadUserByUsername(String userName) {
        UserDto userDto = backgroundAccountService.loadUserByUsername(userName);
        UserInfo userInfo = BeanUtil.copyProperties(userDto, UserInfo.class);
        return Result.getInstance(UserInfo.class).setCode(200).setMsg("查询成功").setData(userInfo);
    }

    @Override
    public Result login(LoginInfo loginInfo) throws HttpRequestMethodNotSupportedException {
        Result login = backgroundAccountService.login(loginInfo.getUsername(), loginInfo.getPassword());
        return login;
    }

    @Override
    public Result logout() {
        Result logout = authClient.logout();
        if (logout.getCode() ==200){
            return Result.getInstance().setCode(200).setMsg("已退出");
        }
        return Result.getInstance().setMsg("退出失败").setCode(500);
    }

    private ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 测试用
     * @return
     */
    @RequestMapping(value = "/test")
    public Result<UserDto> test() throws JsonProcessingException {
        System.out.println("111111111");
        String header = WebUtil.getRequest().getHeader(AuthConstant.USER_TOKEN_HEADER);
        System.out.println(header);
        UserDto userDto = objectMapper.readValue(header, UserDto.class);
        System.out.println(userDto.toString());
        return Result.getInstance(UserDto.class).setMsg("测试成功").setCode(200).setData(userDto);
    }
}

